/*   **********************************************************************  **
 **   Copyright notice                                                       **
 **                                                                          **
 **   (c) 2009, Around(J2)ME				                                 **
 **   All rights reserved.                                                   **
 **                                                                          **
 **   This program and the accompanying materials are made available under   **
 **   the terms of the New BSD License which accompanies this    			 **
 **   distribution.											                 **
 **   A copy is found in the textfile LICENSE.txt							 **
 **                                                                          **
 **   This copyright notice MUST APPEAR in all copies of the file!           **
 **                                                                          **
 **   Main developers:                                                       **
 **     Juri Strumpflohner		http://blog.js-development.com	             **
 **		Matthias Braunhofer		http://matthias.jimdo.com                    **
 **                                                                          **
 **  **********************************************************************  */

package com.aroundj2me.model;

import java.util.Enumeration;
import java.util.Hashtable;

import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

/**
 * This class can be used for persistently storing settings, i.e. username, password
 * etc. First simply create an instance of this class . Then you can try to access
 * to a certain value of a field by the get method. If this field does not exist in 
 * the RecordStore, then null is returned. To add a value of a new field, simply call
 * the put method. Finally, call the save method to store all the fields and values 
 * as RecordStore.
 * @author Matthias Braunhofer
 */
public class Preferences {
	private String recordStoreName;
	private Hashtable hashtable;
	
	/**
	 * Constructs a new Preferences object and reads stored values from the RecordStore
	 * @throws RecordStoreException
	 */
	public Preferences() throws RecordStoreException {
		recordStoreName = "Preferences";
		hashtable = new Hashtable();
		initialize();
	}
	
	/**
	 * Returns the value of a certain key that has been stored into the RecordStore
	 * @param key key that specifies in which data one is interested
	 * @return value of the specified key
	 */
	public String get(String key) {
		return (String)hashtable.get(key);
	}
	
	/**
	 * Stores a value of a certain key into the RecordStore
	 * @param key key that specifies the data
	 * @param value value of the corresponding key
	 */
	public void put(String key, String value) {
		if (value == null) {
			value = "";
		}
		hashtable.put(key, value);
	}
	
	/**
	 * Reads all stored data from the RecordStore
	 * @throws RecordStoreException
	 */
	private void initialize() throws RecordStoreException {
		RecordStore rs = null;
		RecordEnumeration re = null;
		try {
			rs = RecordStore.openRecordStore(recordStoreName, true);
			re = rs.enumerateRecords(null, null, false);
			while (re.hasNextElement()) {
				byte[] raw = re.nextRecord();
				String pref = new String(raw);
				//Parse out the name
				int index = pref.indexOf('|');
				String name = pref.substring(0, index);
				String value = pref.substring(index + 1);
				put(name, value);
			}
		}
		finally {
			if (re != null) re.destroy();
			if (rs != null) rs.closeRecordStore();
		}
	}
	
	/**
	 * Saves changes that have occurred back to the RecordStore
	 * @throws RecordStoreException
	 */
	public void save() throws RecordStoreException {
		RecordStore rs = null;
		RecordEnumeration re = null;
		try {
			rs = RecordStore.openRecordStore(recordStoreName, true);
			re = rs.enumerateRecords(null, null, false);
			//First remove all records
			while (re.hasNextElement()) {
				int id = re.nextRecordId();
				rs.deleteRecord(id);
			}
			//Now save the preferences records
			Enumeration keys = hashtable.keys();
				while (keys.hasMoreElements()) {
					String key = (String)keys.nextElement();
					String value = get(key);
					String pref = key + "|" + value;
					byte[] raw = pref.getBytes();
					rs.addRecord(raw, 0, raw.length);
				}
			}
			finally {
				if (re != null) re.destroy();
				if (rs != null) rs.closeRecordStore();
			}
		}
	}
